import { LoginApi, logout, getInfo } from '@/api/Login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'
import { resetRouter, staticRoutes, allAsyncRoutes, anyRoutes } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menuList: [],
    buttons: []
  }
}

const filterAsyncRoutes = (allRouter, router) => {
  return allRouter.filter((all) => {
    if (router.includes(all.name)) {
      if (all.children && all.children.length) {
        const childrenRouter = filterAsyncRoutes(all.children, router)
        router.children = childrenRouter
      }
      return true
    }
    return false
  })
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    const res = await LoginApi({
      username: username.trim(),
      password: password
    })
    if (res.code === 20000) {
      const { data } = res
      commit('SET_TOKEN', data.token)
      setToken(data.token)
    }
  },

  // get user info
  async getInfo({ commit, state }) {
    const response = await getInfo(state.token)
    if (response.code === 20000) {
      const { data } = response
      if (!data) {
        return new Error('Verification failed, please Login again.')
      }
      const permissionRouter = filterAsyncRoutes(
        allAsyncRoutes,
        response.data.routes
      )
      state.menuList = [...staticRoutes, ...permissionRouter, ...anyRoutes]
      state.buttons = [...response.data.buttons]
      router.addRoutes([...permissionRouter, ...anyRoutes])
      const { name, avatar } = data
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
    }
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
